<template>
  <div :style="{ width: containerWidth, padding: '0 16px' }">
    <div class="header" v-if="config">
      <span>{{ config.info.title }}</span>
    </div>
    <span v-if="!config || !content || !currentContent"></span>
    <!-- Start of Content -->
    <el-card v-if="config && content && currentContent" class="main">
      <div slot="header">
        <span style="font-weight:bold"
          >{{ currentContent.idx }}<span style="font-size:12px">#</span></span
        >
        <el-tag
          size="small"
          type="primary"
          style="float:right;margin-left:12px"
          round
          >{{ currentContent.type }}</el-tag
        >
        <el-tag
          size="small"
          type="primary"
          style="float:right;margin-left:12px"
          >{{ timeString }}</el-tag
        >
      </div>
      <!-- Start of Choice Content -->
      <transition name="el-fade-in">
        <div v-show="!fadeOut">
          <div>{{ currentContent.subject }}</div>
          <div v-if="!fadeOutOut" style="margin-top:18px">
            <el-button
              class="button-wrap"
              :type="
                choiceStatus(option.tag) === -1
                  ? 'danger'
                  : choiceStatus(option.tag) === 1
                  ? 'success'
                  : 'primary'
              "
              v-for="(option, idx) in currentOptions"
              :key="idx"
              @click="setAnswer(option.tag)"
              :style="{
                textAlign: 'justify',
                width: '100%',
                margin: '0 0 10px 0',
                lineHeight: '1.2',
                fontSize: '15px',
                padding: '10px 15px',
              }"
              :plain="choiceStatus(option.tag) === 0"
              :disabled="frozeForward"
            >
              <b v-if="config.isDisorder">#.&nbsp;</b>
              <b v-else>{{ option.tag }}.&nbsp;</b>
              {{ option.text }}
              <!-- <span :style="{fontSize:'24px',width:'40px',minHeight:'24px'}">{{ letters[idx] }}</span> -->
              <!-- <span :style="{fontSize:'15px',width:'calc(100% - 40px)',minHeight:'24px'}">{{ item }}</span> -->
            </el-button>
          </div>
        </div>
      </transition>
      <!-- End of Choice Content -->
    </el-card>
    <!-- End of Content -->
    <!-- Start of Control Bar -->
    <div class="footer" v-if="config && content">
      <el-button
        size="mini"
        plain
        round
        :type="
          answerStatus === 1
            ? 'success'
            : answerStatus === -1
            ? 'danger'
            : 'primary'
        "
        @click="
          showJumper = true;
          clearTimer();
        "
      >
        {{ pointer + 1 }} / {{ config.array.length }}
      </el-button>
      <el-button
        size="mini"
        plain
        round
        :type="
          accuracy >= 0.95 && !isNew
            ? 'success'
            : accuracy < 0.9 && !isNew
            ? 'danger'
            : 'primary'
        "
        @click="
          showNotify = true;
          clearTimer();
        "
      >
        {{ accuracy == 1 ? 100 : (accuracy * 100).toFixed(1) }} %
      </el-button>
      <el-button
        size="mini"
        plain
        round
        :type="enablePrev ? 'primary' : 'info'"
        @click="pointerBackward"
        :disabled="!enablePrev"
      >
        上一题
      </el-button>
      <el-button
        size="mini"
        plain
        round
        :type="enableNext ? 'primary' : 'info'"
        @click="pointerForward"
        :disabled="!enableNext"
      >
        下一题
      </el-button>
    </div>
    <!-- End of Control Bar -->
    <jumper
      :content="content"
      :answersInit="answersInit"
      :sequence="config.array"
      :visible="showJumper"
      @jump="handleJump"
      @close="
        showJumper = false;
        setTimer();
      "
      v-if="loaded && content"
    />
    <notify
      :rate="accuracy"
      :answersInit="answersInit"
      :content="content"
      :finished="isFinished"
      :timeStr="timeString"
      :visible="(isFinished && !notified) || showNotify"
      v-if="loaded && content"
      @close="
        notified = true;
        showNotify = false;
      "
      @return="handleReturn"
      @cancel="
        showNotify = false;
        setTimer();
      "
    />
  </div>
</template>

<script>
import jumper from "./jumper";
import notify from "./notify";
export default {
  name: "workoutView",
  components: {
    jumper,
    notify,
  },
  data() {
    return {
      timer: -1,
      endurance: 0,
      pointer: 0,
      countRight: 0,
      letters: [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
      ],
      answers: [],
      answersInit: [],
      fadeOut: false,
      fadeOutOut: false,
      frozeForward: false,
      isNew: true,
      showJumper: false,
      showNotify: false,
      notified: false,
      loaded: false,
    };
  },
  computed: {
    containerWidth() {
      return this.$store.state.style.containerWidth;
    },
    config() {
      return this.$route.params.config;
    },
    content() {
      return this.$store.state.data.content;
    },
    currentContent() {
      if (!this.config || !this.content) return null;
      return this.content[this.config.array[this.pointer]];
    },
    currentAnswer() {
      if (!this.config || !this.content) return [];
      return this.answers[this.pointer];
    },
    currentAnswerInit() {
      return this.answersInit[this.pointer];
    },
    answerStatus() {
      try {
        if (!this.config || !this.content || !this.currentContent) return 0;
        if (this.currentAnswer === "") return 0;
        //Multiple Choice
        if (this.currentContent.key.length > 1) {
          if (this.currentAnswer.join("") === this.currentContent.key) {
            return 1;
          } else if (
            this.currentContent.key.length == this.currentAnswer.length
          ) {
            let yes = true;
            for (let i = 0; i < this.currentAnswer.length; i++) {
              // if (this.currentContent.key.indexOf(this.currentAnswer[i]) < 0) {
              //   return -1;
              // }
              yes =
                yes & this.currentContent.key.includes(this.currentAnswer[i]);
            }
            return yes;
          } else {
            return 0;
          }
        } else {
          //Single Choice
          if (this.currentAnswer === this.currentContent.key) {
            return 1;
          } else {
            return -1;
          }
        }
      } catch (err) {
        console.log(err);
        return 0;
      }
    },
    isFinished() {
      for (let i = 0; i < this.answersInit.length; i++) {
        if (this.answersInit[i].length === 0) {
          return false;
        }
      }
      this.clearTimer();
      return true;
    },
    enableNext() {
      if (
        this.pointer === this.content.length - 1 ||
        this.isFinished ||
        this.answerStatus < 1 ||
        this.frozeForward
      ) {
        return false;
      } else {
        return true;
      }
    },
    enablePrev() {
      if (this.pointer === 0 || this.isFinished || this.frozeForward) {
        return false;
      } else {
        return true;
      }
    },
    accuracy() {
      try {
        if (!this.content) return 0;
        let count = 0;
        let total = 0;
        for (let i = 0; i < this.answersInit.length; i++) {
          if (this.answersInit[i].length > 0) {
            total++;
            if (
              this.answersInit[i] === this.content[this.config.array[i]].key
            ) {
              count++;
            }
          }
        }
        if (total == 0) return 0.0;
        return (count / total).toFixed(4);
      } catch (e) {
        console.log(e);
        return 0;
      }
    },
    timeString() {
      let str = "";
      let min = parseInt(this.endurance / 60);
      let sec = this.endurance - min * 60;
      str = min + "'" + sec + '"';
      return str;
    },
    currentOptions() {
      if (
        this.currentContent &&
        this.currentContent.options &&
        this.currentContent.options.length > 0
      ) {
        let options = this.currentContent.options.map((text, idx) => {
          return {
            tag: this.letters[idx],
            text: text,
          };
        });
        if (this.config.isDisorder) {
          let i = options.length;
          while (i) {
            let j = Math.floor(Math.random() * i--);
            [options[j], options[i]] = [options[i], options[j]];
          }
        }
        return options;
      }
      return [];
    },
  },
  methods: {
    handleReturn() {
      if (this.$store.state.data.show == "extra") {
        this.$router.push({
          name: "start",
          query: { show: "extra" },
        });
      } else if (this.$store.state.data.show == "full") {
        this.$router.push({
          name: "start",
          query: { show: "full" },
        });
      } else {
        this.$router.push({
          name: "start",
        });
      }
    },
    handleJump(index) {
      this.showJumper = false;
      this.fadeOut = true;
      this.frozeForward = true;
      let that = this;
      setTimeout(function() {
        that.pointer = index;
        that.fadeOut = false;
        that.frozeForward = false;
      }, 300);
    },
    choiceStatus(choice) {
      if (!this.currentContent || !this.currentContent) return 0;
      if (this.currentContent.key.length > 1) {
        //Multiple Choice
        if (this.currentAnswer.indexOf(choice) > -1) {
          if (this.currentContent.key.indexOf(choice) > -1) return 1;
          else return -1;
        } else return 0;
      } else {
        //Single Choice
        if (this.currentAnswer === choice) {
          if (this.currentContent.key === choice) return 1;
          else return -1;
        } else return 0;
      }
    },
    pointerForward() {
      if (this.enableNext) {
        this.fadeOut = true;
        this.frozeForward = true;
        let that = this;
        setTimeout(function() {
          that.pointer++;
          that.fadeOutOut = true;
          that.$nextTick(function() {
            that.fadeOutOut = false;
            that.$nextTick(function() {
              that.fadeOut = false;
              setTimeout(function() {
                that.frozeForward = false;
              }, 300);
            });
          });
        }, 300);
      }
    },
    pointerBackward() {
      if (this.enablePrev) {
        this.fadeOut = true;
        this.frozeForward = true;
        let that = this;
        setTimeout(function() {
          that.pointer--;
          that.fadeOutOut = true;
          that.$nextTick(function() {
            that.fadeOutOut = false;
            that.$nextTick(function() {
              that.fadeOut = false;
              setTimeout(function() {
                that.frozeForward = false;
              }, 300);
            });
          });
        }, 300);
      }
    },
    setAnswer(answer) {
      this.isNew = false;
      if (this.currentContent.key.length > 1) {
        //Multiple Choice
        if (this.currentAnswer === "") {
          this.answers.splice(this.pointer, 1, [answer]);
        } else {
          let ansIdx = this.currentAnswer.indexOf(answer);
          let tmparr = JSON.parse(JSON.stringify(this.currentAnswer));
          if (ansIdx > -1) {
            tmparr.splice(ansIdx, 1);
          } else {
            tmparr.push(answer);
          }
          tmparr.sort();
          this.answers.splice(this.pointer, 1, tmparr);
        }
        //set init answer
        if (this.answerStatus !== 0 && this.currentAnswerInit === "") {
          this.answersInit.splice(this.pointer, 1, this.currentAnswer.join(""));
        }
      } else {
        //Single Choice
        this.answers.splice(this.pointer, 1, answer);
        if (this.currentAnswerInit === "") {
          this.answersInit.splice(this.pointer, 1, answer);
        }
      }
      if (this.config.autoNext && this.answerStatus === 1) {
        this.frozeForward = true;
        const that = this;
        setTimeout(() => {
          that.frozeForward = false;
          that.pointerForward();
        }, 200);
      }
    },
    clearTimer() {
      clearInterval(this.timer);
    },
    setTimer() {
      let that = this;
      this.timer = setInterval(() => {
        that.endurance++;
      }, 1000);
    },
  },
  created() {
    if (!this.config) {
      window.console.log("Missing Config!");
      this.$router.push({ name: "home" });
      return null;
    } else {
      window.console.log("Missing Content!");
      this.$store.dispatch("loadContent", this.config.info.file);
      this.$nextTick(() => {
        this.loaded = true;
        this.pointer = this.config.pointer;
        for (let i = 0; i < this.config.array.length; i++) {
          this.answers.push("");
          this.answersInit.push("");
        }
      });
    }
  },
  mounted() {
    this.endurance = 0;
    this.setTimer();
  },
};
</script>

<style scoped>
.page {
  background-color: #000;
}

.main {
  width: 100%;
  height: calc(100vh - 122px);
  /* margin-top: 60px; */
  overflow-y: auto;
  background-color: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(6px);
  /* border-color: rgba(255, 255, 255, 0.25); */
  /* border: none; */
  /* box-shadow: 30px 0 30px rgba(0, 0, 0, 1); */
}

.header {
  color-scheme: light dark;
  /* position: fixed;
    z-index: 1000;
    top: 0;
    left: 0;
    right: 0; */
  width: 100%;
  height: 60px;
  padding: 0;
  margin: 0;
  display: flex;
  /* justify-content: center; */
  /* 水平居中 */
  align-items: center;
  /* 垂直居中 */
  /* border-bottom: 1px solid white; */
  /* white-space: nowrap; */
  overflow: hidden;
  /* background: rgba(64, 158, 255, 0.75); */
  /* box-shadow: -5px 0 5px rgba(255, 255, 255, 0.75); */
  /* color: #606266; */

  font-weight: bold;
  font-size: 20px;
  text-align: justify;
  /* color: #000;
    text-shadow:
      0 1px 1px rgba(255, 255, 255, 0.5),
      0 -1px 1px rgba(255, 255, 255, 0.5),
      1px 0px 1px rgba(255, 255, 255, 0.5),
      -1px 0px 1px rgba(255, 255, 255, 0.5); */

  color: #fff;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5), 0 -1px 2px rgba(0, 0, 0, 0.5),
    1px 0px 2px rgba(0, 0, 0, 0.5), -1px 0px 2px rgba(0, 0, 0, 0.5);
  /* text-shadow: 0px 0px 3px rgba(0, 0, 0, 1); */
}

.footer {
  /* position: fixed;
    z-index: 1000;
    left: 0;
    right: 0;
    bottom: 0; */
  width: 100%;
  height: 60px;
  padding: 0;
  margin: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
  /* border-top: 1px solid white; */
  font-size: 12px;
  color: grey;
  white-space: nowrap;
  overflow: hidden;
  /* background: rgba(255, 255, 255, 0.75); */
}

.button-wrap {
  word-wrap: break-word !important;
  word-break: break-all !important;
  white-space: normal !important;
  transition: all 0.3s;
}
</style>
